package com.teatime.client.bus.publish.editors;

import com.teatime.client.R;
import com.teatime.client.view.PopupEditor;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class PriceEditor extends PopupEditor {

	private float mPrice;
	private float mOrigPrice;
	
	public PriceEditor(Context context) {
		super(context);
		init();
	}
	
	protected boolean getOff() {
		return true;
	}
	
	@Override
	protected int getContentLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.view_price_editor;
	}
	
	private void init() {
		mPrice = mOrigPrice = -1.0f;
	}
	
	@Override
	protected void onInitViews() {
		if (!getOff()) {
			EditText te = (EditText)findViewById(R.id.txt_edit_pub_orig_price);
			if (te != null) {
				te.setVisibility(View.GONE);
			}
			TextView tv = (TextView)findViewById(R.id.txt_title_pub_orig_price);
			if (tv != null) {
				tv.setVisibility(View.GONE);
			}
		}
	}
	
	@Override
	protected void setControlValues() {
		setPriceValue(R.id.txt_edit_pub_price, mPrice);
		if (getOff()) {
			setPriceValue(R.id.txt_edit_pub_orig_price, mOrigPrice);
		}
	}
	
	@Override
	protected void getControlValues() {
		mPrice = getPriceValue(R.id.txt_edit_pub_price);
		if (getOff()) {
			mOrigPrice = getPriceValue(R.id.txt_edit_pub_orig_price);
		}
	}
	
	private float getPriceValue(int resId) {
		TextView tv = (TextView)findViewById(resId);
		String txt = null;
		if (tv != null) {
			txt = (String)tv.getText().toString();
			if (txt != null && txt != "") {
				try {
					return Float.parseFloat(txt);
				}
				catch(NumberFormatException e){
				}
			}
		}
		return -1.0f;
	}
	
	private void setPriceValue(int resId, float price) {
		TextView tv = (TextView)findViewById(resId);
		if (tv != null) {
			if (price >= 0) {
				tv.setText(Float.toString(price));
			}
			else {
				tv.setText("");
			}
		}
	}
	
	public void setPrice(float price) {
		mPrice = price;
	}
	
	public void setOrigPrice(float oldPrice) {
		mOrigPrice = oldPrice;
	}
	
	public float getPrice() {
		return mPrice;
	}
	
	public float getOrigPrice() {
		return mOrigPrice;
	}
	
	private String getCurrencyUnit() {
		return getContext().getResources().getString(R.string.txt_currency_unit);
	}
	
	public String makeFormatted() {
		String formatted = "";
		Float price = getPrice(), orig = getOrigPrice();

		if (price >= 0) {
			formatted = price.toString() + getCurrencyUnit();
			if (orig >= 0) {
				formatted += "/" + orig.toString() + getCurrencyUnit();
			}
		}
		return formatted;
	}

	@Override
	public void onSaveData(Bundle bundle) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onRestoreData(Bundle bundle) {
		// TODO Auto-generated method stub
		
	}
}
